package net.kongliu.util;

import net.kongliu.util.entity.ObjectError;
import net.kongliu.util.entity.SimpleValidationResult;
import net.kongliu.util.entity.ValidationResult;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

public final class ValidationUtils {
    private final static Validator VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();

    private ValidationUtils() {
        throw new RuntimeException("禁止实例化");
    }

    public static <T> ValidationResult validate(T object, Class<?>... groups) {
        SimpleValidationResult result = new SimpleValidationResult();
        Set<ConstraintViolation<T>> violations = VALIDATOR.validate(object, groups);
        if (violations != null && !violations.isEmpty()) {
            String objectName = object.getClass().getName();
            for (ConstraintViolation<T> violation : violations) {
                ObjectError error = new ObjectError(objectName, violation.getMessage());
                result.addError(error);
            }
            result.setHasErrors(true);
        }
        return  result;
    }

}
